import "./index.css";
import { defineComponent, ref, computed, onMounted, nextTick, Teleport } from "vue";
import { useRouterStoreHook } from "@/store/modules/router";
import { PxButton } from "px-ui";
import { useThrottleFn } from "@vueuse/core";
import { throttleDelay as delay } from "@/utils/constant";

const props = {
  to: {
    type: [String, HTMLElement],
    require: false,
    default: ""
  },
  submitDisabled: {
    type: Boolean,
    require: false,
    default: false
  },
  cancelText: {
    type: String,
    require: false,
    default: "取消"
  },
  submitText: {
    type: String,
    require: false,
    default: "确定"
  },
  // bottom left
  placement: {
    type: [String],
    require: false,
    default: "bottom"
  },
  height: {
    type: Number,
    require: false,
    default: 60
  },
  width: {
    type: Number,
    require: false,
    default: 100
  }
};

const emits = ["cancel", "submit"];

export default defineComponent({
  name: "ReTeleport",
  props,
  emits,
  setup(props, { slots, attrs, emit }) {
    const flag = ref<boolean>(false);

    const to = computed(() => {
      if (props.to) {
        return props.to;
      } else if (props.placement === "left") {
        return "#layoutLeftContent";
      } else {
        return "#layoutBottomBtns";
      }
    });

    const throttleCancel = useThrottleFn(() => emit("cancel"), delay);
    const throttleSubmit = useThrottleFn(() => emit("submit"), delay);

    const init = () => {
      switch (props.placement) {
        case "bottom":
          props.height && useRouterStoreHook().SET_BOTTOM_FOOTER_HEIGHT(props.height);
          break;
        case "left":
          props.width && useRouterStoreHook().SET_LEFT_WIDTH(props.width);
          break;
        default:
          props.height && useRouterStoreHook().SET_BOTTOM_FOOTER_HEIGHT(props.height);
          break;
      }
      setTimeout(() => {
        flag.value = true;
      }, 0);
    };

    onMounted(async () => {
      await nextTick();
      init();
    });

    return () => {
      const defaultBtnsDom = () => {
        // const { cancelText = "取消", submitText = "确定", submitDisabled = false } = props;
        return (
          <div class={"default-btns"}>
            <PxButton onClick={() => throttleCancel()}>{props.cancelText || "取消"}</PxButton>
            <PxButton type={"primary"} disabled={!!props.submitDisabled} onClick={() => throttleSubmit()}>
              {props.submitText || "确定"}
            </PxButton>
          </div>
        );
      };
      return flag.value ? (
        <Teleport to={to.value} {...attrs}>
          {slots?.default ? slots?.default?.() : defaultBtnsDom()}
        </Teleport>
      ) : null;
    };
  }
});
